const baseUrl = 'https://admin.sczgpy.com';
/**
     * 获取到从2020那一年开始至今的年份
     */
   export const getYearsToNow =() =>{
      // this.yearsToNow=[2020,2021,2022]
      //获取到从那一年开始
      let smallYears = 2020
      //获取当前时间
      let date = new Date
      let nowYears = date.getFullYear()
      let Years = nowYears - smallYears
      let arrYear = []
      for (let i = 0; i <= Years; i++) {
        arrYear.unshift(nowYears--)
      }
      // arrYear.forEach(item => {
      //   //下拉框的数组
      //   this.yearsToNow.push(item)
      // })
	  return arrYear
    }
	
	
	//获取当前日期函数
	export const getNowFormatDate =() =>{
	  let date = new Date(),
	    year = date.getFullYear(), //获取完整的年份(4位)
	    month = date.getMonth() + 1, //获取当前月份(0-11,0代表1月)
	    strDate = date.getDate() // 获取当前日(1-31)
	  if (month < 10) month = `0${month}` // 如果月份是个位数，在前面补0
	  if (strDate < 10) strDate = `0${strDate}` // 如果日是个位数，在前面补0
	 
	  return `${year}-${month}-${strDate}`
	}
	
	//时间戳转换方法    date:时间戳数字
	export const  formatDate =(date) =>{
	    console.log(date)
	    var date = new Date(date);
	    var YY = date.getFullYear() + '-';
	    var MM = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-';
	    var DD = (date.getDate() < 10 ? '0' + (date.getDate()) : date.getDate());
	    var hh = (date.getHours() < 10 ? '0' + date.getHours() : date.getHours()) + ':';
	    var mm = (date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes()) + ':';
	    var ss = (date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds());
	    // return YY + MM + DD + " " + hh + mm + ss;
	    return YY + MM + DD;
	  }
	export const  formatTime =(prellTime)=> {
	  				let date = new Date().getTime();
	  				let lefttime = prellTime ,
						leftd = Math.floor(lefttime / ( 60 * 60*24)), //计算小时数
	  					lefth = Math.floor(lefttime / ( 60 * 60)%24), //计算小时数
	  					leftm = Math.floor(lefttime / (1 * 60) % 60), //计算分钟数
	  					lefts = Math.floor(lefttime / 1% 60); //计算秒数
	  				//返回倒计时的字符串
	  				return lefttime >= 0 ? leftd + "天"+[lefth<10?'0'+lefth:lefth] + "小时	" : '0天0时';
	  			}
	
	// 图片上传
	export const uploadFileApi =(tempFilePaths)=> {
	  console.log('tempFilePaths:', tempFilePaths);
	  return new Promise((resolve, reject) => {
	    if ({}.toString.call(tempFilePaths) != '[object Array]') {
	      throw new TypeError(`上传图片参数 tempFilePaths 类型错误!`)
	    }
	    if (tempFilePaths.length == 0) {
	      presolve([])
	      return
	    }
	   uni.showLoading({
	      title: '图片上传中...',
	      mask: true
	    });
	    let uploadArray = [];
	    tempFilePaths.forEach((item, index) => {
			console.log(item)
	      uploadArray[index] = new Promise((resolve, reject) => {
	        uni.uploadFile({
	          url:  'http://pinnonghui.xxzcloud.com/api/user/upload', // 仅为示例，非真实的接口地址
	          filePath: item,
	          name: 'media',
	          formData: {},
	          success(res) {
					console.log(res)
	            resolve(JSON.parse(res.data).data);
	          },
	          fail(err) {
	            console.log('err:', err)
	            uni.hideLoading()
	          }
	        });
	      })
	    })
	    Promise.all(uploadArray).then(res => {
	      resolve(res);
	      uni.hideLoading()
	    }).catch(err => {
	      uni.hideLoading()
	    })
	
	  })
	}
	//判断手机号是否合法
	export const judgeTel =($Tel)=> {
	    var myreg = /^1[3456789]\d{9}$/;
	    if (myreg.test($Tel)) {
	        return true
	    } else {
	        return false
	    }
	}
	// //分享
	// export const onShareAppMessage =(title, path, callback, imageUrl)=> {
	//   //设置一个默认分享背景图片
	//   let defaultImageUrl = '../imges/icon8.png';
	//   return {
	//     title: title,
	//     path: path,
	//     imageUrl: imageUrl || defaultImageUrl,
	//     success(res) { 
	//       console.log("转发成功！");
	//       if (!res.shareTickets) {
	//       	//分享到个人
	//         api.shareFriend().then(() => {
	//           console.warn("shareFriendSuccess!");
	//           //执行转发成功以后的回调函数
	//           callback && callback();
	//         });
	//       } else {
	//       	//分享到群
	//         let st = res.shareTickets[0];
	//         wx.getShareInfo({
	//           shareTicket: st,
	//           success(res) {
	//             let iv = res.iv
	//             let encryptedData = res.encryptedData;
	//             api.groupShare(encryptedData, iv).then(() => {
	//               console.warn("groupShareSuccess!");
	//               //执行转发成功以后的回调函数
	//               callback && callback();
	//             });
	//           }
	//         });
	//       }
	//     },
	//     fail: function (res) {
	//       console.log("转发失败！");
	//     }
	//   };
	// }
	
	
	
	// 将时间戳转化为时分秒的格式，一般用作倒计时
	export const intervalTime = (endTime) => {
		console.log(endTime,222)
		// var timestamp=new Date().getTime(); //计算当前时间戳
		var date1 = (Date.parse(new Date()))/1000;//计算当前时间戳 (毫秒级)
		var date2 = endTime; //结束时间
		// var date3 = date2.getTime() - date1.getTime(); //时间差的毫秒数
		var date3 =  (date2- date1)*1000; //时间差的毫秒数
		//计算出相差天数
		var days = Math.floor(date3 / (24 * 3600 * 1000));
		//计算出小时数
	 
		var leave1 = date3 % (24 * 3600 * 1000); //计算天数后剩余的毫秒数
		var hours = Math.floor(leave1 / (3600 * 1000));
		//计算相差分钟数
		var leave2 = leave1 % (3600 * 1000); //计算小时数后剩余的毫秒数
		var minutes = Math.floor(leave2 / (60 * 1000));
	 
		//计算相差秒数
	 
		var leave3 = leave2 % (60 * 1000); //计算分钟数后剩余的毫秒数
		var seconds = Math.round(leave3 / 1000);
	    // console.log(days + "天 " + hours + "小时 ")
		var sun = days*24 + hours;
		var min = minutes;
		var sec = seconds;
		if(sun == 0){
			sun = '00';
		}else if(sun < 10){
			sun = '0'+sun;
		}
		if(min < 10){
			min = '0'+minutes;
		}
		if(sec < 10){
			sec = '0'+seconds;
		}
		
		// if((days*24 + hours)<= 0 && minutes <= 0 && seconds <= 0){
			
		// 	return '00.00.00'
		// }else{
		// 	return   (sun) + "." + min + "." + sec;
		// }
		return   days + "天 " + hours + "小时 "
	}

export 	const timestampToTime = (timestamp)=>{
		var date = new Date(timestamp );//时间戳为10位需*1000，时间戳为13位的话不需乘1000
		let Y = date.getFullYear() + '-';
		let M = (date.getMonth()+1 < 10 ? '0'+(date.getMonth()+1) : date.getMonth()+1) + '-';
		let D = (date.getDate()  < 10 ? '0'+(date.getDate()) : date.getDate()) + ' ';
		let h = (date.getHours() < 10 ? '0'+(date.getHours()) : date.getHours()) + ':';
		let m = (date.getMinutes() < 10 ? '0'+(date.getMinutes()) : date.getMinutes()) + '';
		// let s = date.getSeconds();
		console.log(Y+M+D+h+m)
		return Y+M+D+h+m;
	}

export	const getRichtext=(html)=> {
		let newContent = html.replace(/<img[^>]*>/gi, function(match, capture) {
			match = match.replace(/style="[^"]+"/gi, '').replace(/style='[^']+'/gi, '');
			match = match.replace(/width="[^"]+"/gi, '').replace(/width='[^']+'/gi, '');
			match = match.replace(/height="[^"]+"/gi, '').replace(/height='[^']+'/gi, '');
			// match = match.replace(/\<td /gi, `<td  style="width: 100%;border:1rpx solid grey" border="0" cellspacing="1" cellpadding="0"`);
			return match;
		});
		newContent = newContent.replace(/style="[^"]+"/gi, function(match, capture) {
			match = match.replace(/width:[^;]+;/gi, 'max-width:100%;').replace(/width:[^;]+;/gi,
				'max-width:100%;');
			return match;
		});
		// newContent = newContent.replace(/<br[^>]*\/>/gi, '');
		newContent = newContent.replace(/\<img/gi,
			'<img style="max-width:100%;height:auto;display:block;margin-top:0;margin-bottom:0;margin:auto"'
		);
		// newContent = newContent.replace(/\<td /gi, `<td  style="width: 100%; border="1rpx" cellspacing="1" cellpadding="0"`);
		return newContent;
	}

	// 登录检查
export	const checkLogin=()=> {
		// 优先检查H5登录状态
		const h5LoginData = uni.getStorageSync('h5_login_data');
		if (h5LoginData) {
			try {
				const loginData = JSON.parse(h5LoginData);
				if (loginData.token && loginData.user_id) {
					return true;
				}
			} catch (e) {
				console.error('解析H5登录数据失败:', e);
			}
		}
		
		// 检查小程序登录状态
		const token = uni.getStorageSync('token');
		if (!token) {
			uni.showToast({
				title: '请登录',
				icon: 'none'
			});
			setTimeout(() => {
				uni.navigateTo({
					url: `/pages/login/h5login`
				})
			}, 1200)
		} else {
			return true;
		}
	}